const app = getApp();
const api = app.apiInstance;
import { ILLEGALTYPEARRAY } from "../../public/utils/const.js";
const {
  htmlDecode
} = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: app.globalData.baseUrl,
    fileUrl: app.globalData.fileUrl,
    illegal: {},
    illegalTypeArray: ILLEGALTYPEARRAY,
    nodeArray: ['申请退回', '指派责任部门', '指派处理', '隐患排除中', '整改后审核', '闭环'],
    illegalLevelArray: ['一般', '重大'],
    deptList: [],
    staffList: [],
    fixImgList: [],
    afterPic: null,
    illegalId: null,
    dealFlag: null,
    ssoFlag: null,
    user: wx.getStorageSync('userinfo').siocCnName,
    applyDate: new Date().toISOString().substring(0, 10),
    flowType: null,
    flowId: null,
    deptIndex: null,
    staffIndex: null,
    deadlineIndex: null,
    apply: false,
    fixDone: false,
    bigSearchShow: false,
    bigSearchType: "",
    corrector: "",
    dept: "",
    searchDataList: []
  },
  

  getAllDept: function () {
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/deptInfo/wx/getAllDept',
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('获取所有部门信息:', res.data);
        var data = res.data;
        that.setData({
          deptList: data.data
        })
      }
    });
  },

  getStaffByDept: function (dutyDept) {
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/staffInfo/wx/getStaffByDept?dept=' + dutyDept,
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('获取部门员工信息:', res.data);
        var data = res.data;


        that.setData({
          staffList: data.data,
        })

      }
    });
  },

  searchSelect(e) {
    const params = {}
    params[this.data.bigSearchType == 'staff' ? 'corrector' : 'dept'] = e.detail.name

    this.setData({
      ...params
    })
  },

  DateChange: function (e) {
    this.setData({
      applyDate: e.detail.value
    })
  },

  DelImg(e) {
    wx.showModal({
      title: '删除图片',
      content: '确定要删除这张图片',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.fixImgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            fixImgList: this.data.fixImgList
          })
        }
      }
    })
  },
  ChooseImage: function () {
    var that = this;
    wx.chooseMedia({
      count: 1, // 一次只能选择一张图片
      sizeType: ['original', 'compressed'], // 压缩图片
      sourceType: ['album', 'camera'], // 从相册选择
      success(res) { // 将图片上传到服务器
        wx.uploadFile({
          url: that.data.fileUrl + '/common/picUpload', // 上传的服务器地址
          filePath: res.tempFiles[0].tempFilePath, // 图片的本地地址
          name: 'file', // 服务端用于接收文件的参数名
          success(res) {
            let json = JSON.parse(res.data);
            let tempArray = [];
            tempArray.push(json.fileName);
            // 上传成功，做一些处理
            if (that.data.fixImgList.length != 0) {
              that.setData({
                fixImgList: that.data.fixImgList.concat(tempArray)
              })
            } else {
              that.setData({
                fixImgList: tempArray
              })
            }
          }
        })
      }
    })
  },
  getIllegalInfo: function (illegalId) {
    var that = this;

    api.get('/illegalRecord/wx/' + illegalId).then(res => {
      var data = res;

      data.data.location = htmlDecode(data.data.location)
      data.data.content = htmlDecode(data.data.content)

      that.setData({
        illegal: data.data,
        imgList: data.data.imgList,
        fixImgList: data.data.fixImgList
      });
      if (1 == that.data.flowType) {
        that.getStaffByDept(data.data.dept);
      }
    });

  },

  chooseImage: function () {
    var that = this;
    wx.chooseMedia({
      count: 1, // 一次只能选择一张图片
      sizeType: ['compressed'], // 压缩图片
      sourceType: ['camera'], // 从相册选择
      success(res) { // 将图片上传到服务器
        wx.uploadFile({
          url: that.data.fileUrl + '/common/picUpload', // 上传的服务器地址
          filePath: res.tempFiles[0].tempFilePath, // 图片的本地地址
          name: 'file', // 服务端用于接收文件的参数名
          success(res) {
            // 上传成功，做一些处理
            let json = JSON.parse(res.data);
            console.log('上传图片结果', res.data)
            that.setData({
              afterPic: that.data.fileUrl + json.fileName,
              fixDone: true
            })
          }
        })
      }
    })
  },

  deptChange: function (e) {
    console.log('部门选择改变，携带值为', e)
    this.setData({
      deptIndex: e.detail.value
    })
  },

  staffChange: function (e) {
    console.log('部门选择改变，携带值为', e)
    this.setData({
      staffIndex: e.detail.value
    })
  },

  submitForm(e) {
    var that = this;
    const formData = e.detail.value;
    var errMsg = "";
    var endPoint = "";
    // 指派责任部门
    if (that.data.flowType == 0) {
      if (!formData.dept) {
        errMsg = errMsg + "责任部门不能为空;";
      }

      if (errMsg.length > 0) {
        wx.showModal({
          title: '提示',
          content: errMsg,
          showCancel: false
        })
        return;
      }
      endPoint = "/rmStaff/wx/passPropose";
    }
    //指派整改人
    if (that.data.flowType == 1) {
      if (!formData.corrector) {
        errMsg = errMsg + "整改人不能为空;";
      }
      if (errMsg.length > 0) {
        wx.showModal({
          title: '提示',
          content: errMsg,
          showCancel: false
        })
        return;
      }
      endPoint = "/illegalRecord/wx/assignPerson";
      console.log('formData', formData);
      formData.dept = that.data.illegal.dept;
    }
    //整改
    if (that.data.flowType == 2) {

      formData.fixImgList = that.data.fixImgList;
      if (formData.fixImgList.length < 1) {
        errMsg = errMsg + "整改图片不能为空;";
      }
      if (errMsg.length > 0) {
        wx.showModal({
          title: '提示',
          content: errMsg,
          showCancel: false
        })
        return;
      }
      endPoint = "/illegalRecord/wx/fixDone";
    }

    formData.handleBy = that.data.user;
    // 向服务器提交表单数据
    console.log('form发生了submit事件，携带数据为：', formData);
    api.post(endPoint, formData).then(res => {
      if (200 == res.code) {
        wx.showModal({
          title: '提示',
          content: res.msg,
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.reLaunch({
                url: '/pages/illegal-list/illegal-list'
              })
            }
          }
        })
      }
    })


  },

  refuse() {
    var that = this;
    wx.showModal({
      editable: true, //显示输入框
      placeholderText: '输入退回原因', //显示输入框提示信息
      success: res => {
        if (res.confirm) { //点击了确认
          console.log(res.content) //用户输入的值
          wx.request({
            url: that.data.baseUrl + '/illegalRecord/wx/refuse',
            method: 'POST',
            data: {
              'illegalId': that.data.illegalId,
              'flowId': that.data.flowId,
              'remark': res.content,
              'flowType': that.data.flowType,
              'handleBy': that.data.user
            },
            success: function (res) {
              console.log('表单提交成功', res);
              if (200 == res.data.code) {
                wx.showModal({
                  title: '提示',
                  content: res.data.msg,
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      wx.reLaunch({
                        url: '/pages/illegal-list/illegal-list'
                      })
                    }
                  }
                })
              } else {
                wx.showToast({
                  title: '提交失败',
                  icon: 'none'
                });
              }
            },
            fail: function (err) {
              console.error('表单提交失败', err);
              wx.showToast({
                title: '表单提交失败',
                icon: 'none'
              });
            }
          });
        } else {
          console.log('用户点击了取消')
        }
      }
    })
  },
  deadlineChange: function (e) {
    console.log('期限选择变化，携带值为', e.detail.value)
    this.setData({
      deadlineIndex: e.detail.value
    })
  },
  ViewImage(e) {
    let urls = [];
    const mediaType = ['mp4', 'avi', 'rmvb', 'flv'];
    let current = this.data.fileUrl + e.currentTarget.dataset.url;

    if (mediaType.includes(current.split('.').pop())) {
      wx.previewMedia({
        sources: [{
          url: current,
          type: 'video',
        }],
      })
      return;
    }

    const imgList = this.data.imgList.filter(item => mediaType.indexOf(item.split('.').pop()) < 0)

    for (let key in imgList) {
      urls.push(this.data.fileUrl + imgList[key]);
    };

    wx.previewImage({
      urls: urls,
      current: current
    });
  },
  ViewImage2(e) {
    let urls = [];
    let current = this.data.fileUrl + e.currentTarget.dataset.url;
    for (let key in this.data.fixImgList) {
      urls.push(this.data.fileUrl + this.data.fixImgList[key]);
    };
    wx.previewImage({
      urls: urls,
      current: current
    });
  },
  passAudit() {
    var that = this;
    var tempFlowType = that.data.flowType;
    var endPoint = '';

    console.log('tempFlowType',tempFlowType);

    if (4 == tempFlowType) {
      endPoint = 'passPostpone';
    }
    if (3 == tempFlowType) {
      endPoint = 'passAudit';
    }

    wx.request({
      url: that.data.baseUrl + '/illegalRecord/wx/' + endPoint,
      method: 'POST',
      data: {
        'illegalId': that.data.illegalId,
        'flowId': that.data.flowId,
        'handleBy': that.data.user
      },
      success: function (res) {
        console.log('表单提交成功', res);
        if (200 == res.data.code) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.reLaunch({
                  url: '/pages/illegal-list/illegal-list'
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: '提交失败',
            icon: 'none'
          });
        }
      },
      fail: function (err) {
        console.error('表单提交失败', err);
        wx.showToast({
          title: '表单提交失败',
          icon: 'none'
        });
      }
    });
  },
  goRiskFlow() {
    var that = this;
    wx.navigateTo({
      url: '/pages/illegal-flow/illegal-flow?illegalId=' + that.data.illegalId,
    })
  },
  doBigSearchShow(e) {
    console.log('e', e);
    const tempArray = [];
    const typeMethods = {
      staff: () => {
        if (this.data.staffList.length == 0) {
          wx.showToast({
            title: '暂无整改人指派',
            icon: 'none'
          });
          return;
        } else {
          this.data.staffList.forEach(item => {
            tempArray.push({
              name: item
            });
          });
        }
      },

      dept: () => {
        if (this.data.deptList.length == 0) {
          wx.showToast({
            title: '暂无部门指派',
            icon: 'none'
          });
          return;
        } else {
          this.data.deptList.forEach(item => {
            tempArray.push({
              name: item
            });
          });
        }
      }
    }
    typeMethods[e.currentTarget.dataset.type]();

    this.setData({
      bigSearchType: e.currentTarget.dataset.type,
      bigSearchShow: true,
      searchDataList: tempArray
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('options', options);
    this.getIllegalInfo(options.illegalId);
    this.setData({
      illegalId: options.illegalId,
      dealFlag: options.dealFlag,
      flowType: options.flowType,
      flowId: options.flowId
    });
    if (options.flowType == 0) {
      this.getAllDept();
    };
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})